package com.cmw.core.base.exception;

import java.io.File;
import java.util.Date;

import com.cmw.core.kit.file.FileUtil;
import com.cmw.core.util.DateUtil;
import com.cmw.core.util.StringHandler;
import com.cmw.core.util.SystemUtils;

/**
 * 异常日志管理类
 * @author chengmingwei
 * @date 2014-12-31
 */
public class ExceptionLogManger {
	/**
	 * 异常对象
	 */
	private Throwable trowable;
	
	public ExceptionLogManger(Throwable trowable) {
		super();
		this.trowable = trowable;
	}

	/**
	 * 打印堆栈信息并保存到 classes 下的 logs 文件夹中
	 * @param isPrintStackTraceInfo 
	 * 	是否打印堆栈信息到控制台 
	 * 	boolean 值 [true : 打印异常并同时将异常记录到日志文件中 ，false:只把异常记录到日志文件中]
	 */
	public void printStackTrace(boolean isPrintStackTraceInfo) {
		StringBuilder sbMsg = new StringBuilder();
		String msg = trowable.getMessage();
		trowable.printStackTrace();
		sbMsg.append("Error : "+msg +"\n");
		StackTraceElement[] stackArr = trowable.getStackTrace();
	
		for(StackTraceElement stack : stackArr){
			String emsg = stack.toString();
			sbMsg.append("\tat "+emsg+"\n");
		}
		String exeTrace = sbMsg.toString();
		writeLogFile(exeTrace);
	}
	
	/**
	 * 将异常信息写入 classes/logs 目录下
	 * @param exeTrace
	 */
	private void writeLogFile(String exeTrace){
		String classesPath = StringHandler.getClassPath();
		if(!SystemUtils.isWindows()) classesPath = File.separator + classesPath;
		Date today = new Date();
		String monthDir = DateUtil.dateFormatToStr(DateUtil.DATE_YYYYMM_FORMAT, today);
		boolean isexist = false;
		String logsDir = classesPath+"logs";
		isexist = FileUtil.exist(logsDir);
		if(!isexist) FileUtil.creatDictory(logsDir);
		
		monthDir = logsDir+File.separator+monthDir;
		isexist = FileUtil.exist(monthDir);
		if(!isexist) FileUtil.creatDictory(monthDir);
		
		String fileName = DateUtil.dateFormatToStr(DateUtil.DATE_TIME_FORMAT, today)+".log";
		String absFileName = monthDir + File.separator+fileName;
		FileUtil.writeStrToFile(absFileName, exeTrace);
	}
}
